#!/bin/bash

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/common.sh"

function install_development() {
  sudo yum install -y wget tar patch Cython cmake git samtools
  source /etc/profile
}

function download_rmats() {
  echo "# rmats正在下载"

  wget -t 10 -T 20 -c -O "$1"/rMATS_v4.1.2.tar.gz \
    https://github.com/Xinglab/rmats-turbo/releases/download/v4.1.2/rmats_turbo_v4_1_2.tar.gz

  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# rmats已经下载成功\033[0m"
  else
    echo -e "\033[31m# rmats下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_rmats() {
  echo "# rmats正在安装"
  tar -xzf "$1"/rMATS_v4.1.2.tar.gz -C "$1" && rm -rf "$1"/rMATS_v4.1.2.tar.gz
  cp "${SCRIPT_DIR}"/Makefile.rMATS_C.patch "$1"/rmats_turbo_v4_1_2/rMATS_C
  cp "${SCRIPT_DIR}"/Makefile-lbfgs_scipy.patch "$1"/rmats_turbo_v4_1_2/rMATS_C/lbfgs_scipy
  cd "$1"/rmats_turbo_v4_1_2
  
  # 修改bamtool编译参数
  sed -i 's/cmake/cmake -D CMAKE_C_COMPILER=clang -D CMAKE_CXX_COMPILER=clang++/' Makefile
  
  # 修改rmats_pipeline编译参数
  sed -i -e 's/# export FC="$(which gfortran)" || return 1/export FC="$(which flang)" || return 1/' \
       -e 's/# export CC="$(which gcc)" || return 1/export CC="$(which clang)" || return 1/' \
	   -e 's/# export CXX="$(which g++)" || return 1/export CXX="$(which clang++)" || return 1/' \
       setup_environment.sh
	   
  # 修改rMATS_C编译参数
  patch -p0 <./rMATS_C/Makefile.rMATS_C.patch
  patch -p0 <./rMATS_C/lbfgs_scipy/Makefile-lbfgs_scipy.patch
  ./build_rmats --no-paired-model
  echo -e "\033[1;32;1m# rmats已经安装完毕\033[0m"
}

function mk_rmats() {
  mkdir -p "$2"/rmats-4.1.2 && cp -r "$1"/rmats_turbo_v4_1_2/* "$2"/rmats-4.1.2
}

function main() {
  set_script_dir
  set -e
  is_check_build_install_directory "$1" "$2" "rmats-4.1.2.sh"
  is_check_build_equal "$1" "$2"
  install_development
  download_rmats "$1"
  install_rmats "$1" "$2"
  mk_rmats "$1" "$2"
  rm -rf "$1"/rmats-4.1.2
}

main "$@"
